// pages/square/square.ts
import {storeBindingsBehavior} from "mobx-miniprogram-bindings"
import {dynamicStore} from "@store/dynamic"
import {getDynamicBehavior} from "@mixin/dynamic"
import { FormEvent } from "miniprogram/@types/Event"
Component({
  /**
   * 绑定状态
   */
  behaviors:[storeBindingsBehavior,getDynamicBehavior],
  storeBindings:{
    store:dynamicStore,
    fields:["dynamicList","dynamicForm"],
    actions:["addDynamicList","resetDynamicList","setDynamicForm","setDynamicList"]
  },
  /**
   * 页面的初始数据
   */
  data: {
    dynamicTypes:["最近","最新","比赛","分类4"],
    scrollHeight:0,
    total:0,
    pulldownStatus:false,
    reachButtom:false,
    last:false,
  },
 
  methods:{
    async searchDynamic(e:FormEvent<null>){
      this.resetDynamicList()
      await this.setDynamicForm({searchKey:e.detail.value})
      await this.getdynamic()
    },
    loveDynamic(e:FormEvent<{index:number}>){
      const dynamicList=this.data.dynamicList
      const index=e.currentTarget.dataset.index
      if(dynamicList[index].islove){
        dynamicList[index].lovenumber--
      }else{
        dynamicList[index].lovenumber++
      }
      dynamicList[index].islove=!dynamicList[index].islove
      this.setData({
        dynamicList
      })
      this.setDynamicList(dynamicList)
    },
    createDynamic(){
      wx.navigateTo({
        url:"/pages/dynamic/create-dynamic/create-dynamic"
      })
    },
    getType(e){
      this.resetDynamicList()
      this.setDynamicForm({type:e.detail.title})
      this.getdynamic()
    },
    async onPullDownRefresh() {
      if(!this.data.pulldownStatus){
        this.setData({
          pulldownStatus:true
        })
        this.resetDynamicList()
        await this.getdynamic()
        this.setData({
          pulldownStatus:false
        })
      }

    },
    async onReachBottom(){
      if(!this.data.reachButtom){
       try{
        this.setData({
          reachButtom:true
        })
        this.setDynamicForm({page:this.data.dynamicForm.page+1})
        await this.getdynamic()
       }finally{
          this.setData({
            reachButtom:false
          })
       }
        
      }
    },
    init(){
      const that=this
      wx.createSelectorQuery().in(this).select("#scroll-box").boundingClientRect().exec((rect)=>{
      if(!!rect){
        const [{height}]=rect
          that.setData({
            scrollHeight:height
          })
      }
    })
    },
},
  /**
   * 生命周期函数--监听页面加载
   */
  attached() {
    this.resetDynamicList()
    this.getdynamic()
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  ready() {
    this.init()
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
 async onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
   
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
   
  }
})